package com.comp6521.project01;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class LiPhaseOne {
	
	private final int amountOnce = 550000;
	
	public List<String> generateSortedFile(String inputFile, String outputFolder) {
		List<String> fileNameList = new ArrayList<String>();
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(inputFile));
			String tempString = null;
			int line = 0;
			int[] array = new int[amountOnce];
			while ((tempString = reader.readLine()) != null) {
				//System.out.println("line " + line + ": " + tempString);
				array[line % amountOnce] = Integer.parseInt(tempString);
				if(line % amountOnce == amountOnce -1){
					String fileNO = (line/amountOnce)<10 ? "0"+ line/amountOnce : String.valueOf(line/amountOnce);
					String fileName = outputFolder+ "/tmp"+ fileNO+".dat";
					writeData(array, line%amountOnce+1, fileName,fileNameList);
				}
				line++;
			}
			String fileNO = (line/amountOnce)<10 ? "0"+ line/amountOnce : String.valueOf(line/amountOnce);
			String fileName = outputFolder+ "/tmp"+ fileNO+".dat";
			writeData(array, line%amountOnce, fileName, fileNameList);
			reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} 
					catch (IOException e1) {
					}
	            }
				return fileNameList;
	        }
	}
	
	
	private void writeData(int[] array, int length, String fileName, List<String> fileNames) throws IOException{
		Quicksort.quickSort(array, length);
		BufferedWriter output = new BufferedWriter(new FileWriter(fileName));
		for(int i=0;i<length;i++){
			output.write(String.valueOf(array[i]));
			output.write("\r\n");
		}
		output.close();	
		fileNames.add(fileName);
		array = new int[amountOnce];
	}


}
